<template>
  <Teleport to="body">
    <Transition name="fade">
      <div v-if="modelValue" class="modal-overlay" @click.self="close">
        <div class="modal-box" :style="{ width }">
          <h2 v-if="title" class="modal-title">{{ title }}</h2>
          <div class="modal-content">
            <slot></slot>
          </div>
          <div class="modal-actions">
            <button class="btn cancel" @click="close">取消</button>
            <button class="btn confirm" @click="$emit('confirm')">确认</button>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    title?: string;
    width?: string;
  }>(),
  {
    width: '400px',
  },
);

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
  (e: 'confirm'): void;
}>();

function close() {
  emit('update:modelValue', false);
}
</script>

<style scoped>
/* 遮罩层 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

/* 弹框主体 */
.modal-box {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  min-width: 300px;
  max-width: 80%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

/* 标题 */
.modal-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: bold;
}

/* 内容区 */
.modal-content {
  margin-bottom: 16px;
}

/* 底部按钮 */
.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.btn {
  padding: 6px 14px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn.cancel {
  background: #e0e0e0;
  color: #333;
}

.btn.cancel:hover {
  background: #d0d0d0;
}

.btn.confirm {
  background: #007bff;
  color: #fff;
}

.btn.confirm:hover {
  background: #0069d9;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
